<template>
  <div class="view-log">
    <!-- 搜索和筛选 -->
    <v-card class="mb-6">
      <v-card-text>
        <v-row>
          <v-col cols="12" md="3">
            <v-text-field
              v-model="search.keyword"
              label="用户名/用户ID"
              prepend-icon="mdi-magnify"
              outlined
              dense
              hide-details
            ></v-text-field>
          </v-col>
          
          <v-col cols="12" md="4">
            <v-row>
              <v-col cols="6">
                <v-menu
                  v-model="startDateMenu"
                  :close-on-content-click="false"
                  transition="scale-transition"
                  min-width="auto"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-text-field
                      v-model="search.startDate"
                      label="开始日期"
                      prepend-icon="mdi-calendar"
                      readonly
                      v-on="on"
                      v-bind="attrs"
                      outlined
                      dense
                      hide-details
                    ></v-text-field>
                  </template>
                  <v-date-picker
                    v-model="search.startDate"
                    @input="startDateMenu = false"
                    :max="maxDate"
                  ></v-date-picker>
                </v-menu>
              </v-col>
              <v-col cols="6">
                <v-menu
                  v-model="endDateMenu"
                  :close-on-content-click="false"
                  transition="scale-transition"
                  min-width="auto"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-text-field
                      v-model="search.endDate"
                      label="结束日期"
                      prepend-icon="mdi-calendar"
                      readonly
                      v-on="on"
                      v-bind="attrs"
                      outlined
                      dense
                      hide-details
                    ></v-text-field>
                  </template>
                  <v-date-picker
                    v-model="search.endDate"
                    @input="endDateMenu = false"
                    :max="maxDate"
                  ></v-date-picker>
                </v-menu>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
        <v-row class="mt-4">
          <v-col cols="12" class="d-flex justify-end">
            <v-btn color="primary" @click="fetchData">
              <v-icon left>mdi-refresh</v-icon>
              查询
            </v-btn>
          </v-col>
        </v-row>
      </v-card-text>
    </v-card>

    <!-- 数据表格 -->
    <v-card>
      <v-data-table
        :headers="headers"
        :items="logs"
        :loading="loading"
        :items-per-page="itemsPerPage"
        :page.sync="page"
        :server-items-length="totalItems"
        class="elevation-1"
        hide-default-footer
      >
        <template v-slot:item.role="{ item }">
          {{ item.role === '0' ? '专家' : '投标人' }}
        </template>
      </v-data-table>

      <!-- 自定义分页 -->
      <div class="d-flex align-center justify-space-between pa-4">
        <v-pagination
          v-model="page"
          :length="Math.ceil(totalItems / itemsPerPage)"
          :total-visible="7"
          circle
        ></v-pagination>
        <v-select
          v-model="itemsPerPage"
          :items="[5, 10, 20, 50]"
          label="每页条数"
          dense
          style="max-width: 120px"
          hide-details
          outlined
        ></v-select>
      </div>
    </v-card>
  </div>
</template>

<script>
import { GetViewLogPage } from '@/api/ViewLog'

export default {
  name: 'ViewLog',
  data() {
    return {
      loading: false,
      startDateMenu: false,
      endDateMenu: false,
      // 分页
      page: 1,
      itemsPerPage: 10,
      totalItems: 0,
      // 查询条件
      search: {
        keyword: '',
        status: '',
        startDate: '',
        endDate: ''
      },
      // 表头（Vuetify2 使用 text/value）
      headers: [
        { text: '用户名', value: 'UserName' },
        { text: '用户Id', value: 'UserId' },
        { text: 'IP', value: 'IP' },
        { text: '查看内容', value: 'Content' },
        { text: '查看时间', value: 'CreateTime' }
      ],
      logs: []
    }
  },
  computed: {
    // 最大允许日期（今天）
    maxDate() {
      return this.getToday()
    }
  },
  watch: {
    // 页码变化重新拉取
    page() {
      this.fetchData()
    },
    // 每页条数变化时重置页码并拉取
    itemsPerPage(val, oldVal) {
      if (val !== oldVal) this.page = 1
      this.fetchData()
    }
  },
  mounted() {
    const today = this.getToday()
    this.search.startDate = today.substring(0, 7) + '-01'
    this.search.endDate = today
    this.fetchData()
  },
  methods: {
    // 获取今天 yyyy-MM-dd
    getToday() {
      const d = new Date()
      const yyyy = d.getFullYear()
      const mm = String(d.getMonth() + 1).padStart(2, '0')
      const dd = String(d.getDate()).padStart(2, '0')
      return `${yyyy}-${mm}-${dd}`
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.page,
          pageSize: this.itemsPerPage,
          key: this.search.keyword,
          start: this.search.startDate,
          end: this.search.endDate
        }
        const res = await GetViewLogPage(params)
        this.logs = (res && res.Data && res.Data.Data) ? res.Data.Data : []
        this.totalItems = (res && res.Data && res.Data.Count) ? res.Data.Count : 0
      } catch (error) {
        console.error('获查看记录失败:', error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.view-log {
  padding: 24px 0;
}
</style>